using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace LibraryManagementSystem
{
    public partial class BookManagementControl : UserControl
    {
        private readonly BookService _bookService;
        private List<Book> _books;
        private List<BookCategory> _categories;

        public BookManagementControl()
        {
            InitializeComponent();
            _bookService = new BookService();
            
            this.btnSearch.Click += new EventHandler(this.btnSearch_Click);
            
            this.Load += BookManagementControl_Load;
        }

        private void BookManagementControl_Load(object sender, EventArgs e)
        {
            LoadCategories();
            LoadBooks();
            SetupListViewColumns();
        }

        private void LoadCategories()
        {
            _categories = _bookService.GetAllCategories();
            cmbCategory.Items.Clear();
            cmbCategory.Items.Add(new ComboBoxItem { Text = "所有分类", Value = null });
            foreach (var category in _categories)
            {
                cmbCategory.Items.Add(new ComboBoxItem { Text = category.CategoryName, Value = category.Id });
            }
            cmbCategory.DisplayMember = "Text";
            cmbCategory.ValueMember = "Value";
            cmbCategory.SelectedIndex = 0;
        }

        private void LoadBooks(string searchKeyword = "", int? categoryId = null)
        {
            if (string.IsNullOrEmpty(searchKeyword) && !categoryId.HasValue)
            {
                _books = _bookService.GetAllBooks();
            }
            else
            {
                _books = _bookService.SearchBooks(searchKeyword, categoryId);
            }
            DisplayBooks();
        }

        private void SetupListViewColumns()
        {
            lvBooks.View = View.Details;
            lvBooks.FullRowSelect = true;
            lvBooks.GridLines = true;
            if (lvBooks.Columns.Count == 0)
            {
                lvBooks.Columns.Add("ISBN", 120);
                lvBooks.Columns.Add("书名", 200);
                lvBooks.Columns.Add("作者", 120);
                lvBooks.Columns.Add("出版社", 150);
                lvBooks.Columns.Add("分类", 100);
                lvBooks.Columns.Add("出版日期", 100);
                lvBooks.Columns.Add("价格", 80);
                lvBooks.Columns.Add("页数", 60);
                lvBooks.Columns.Add("状态", 80);
            }
        }

        private void DisplayBooks()
        {
            lvBooks.Items.Clear();
            foreach (var book in _books)
            {
                var item = new ListViewItem(book.ISBN);
                item.SubItems.Add(book.Title);
                item.SubItems.Add(book.Author);
                item.SubItems.Add(book.Publisher);
                item.SubItems.Add(book.Category?.CategoryName ?? "未分类");
                item.SubItems.Add(book.PublishDate?.ToString("yyyy-MM-dd") ?? "");
                item.SubItems.Add(book.Price?.ToString("C") ?? "");
                item.SubItems.Add(book.Pages?.ToString() ?? "");
                item.SubItems.Add(book.Status ?? "在馆");
                item.Tag = book;
                lvBooks.Items.Add(item);
            }
            lblTotalBooks.Text = $"总共 {_books.Count} 本图书";
        }

        /// <summary>
        /// 获取图书的状态详情（已不使用，保留代码供参考）
        /// </summary>
        /// <param name="book">图书对象</param>
        /// <returns>格式化的状态信息</returns>
        private string GetBookStatus(Book book)
        {
            // 直接返回图书状态
            return book.Status ?? "在馆";
            
            /* 旧的根据副本状态计算的逻辑，不再使用
            if (book.Items == null || !book.Items.Any())
                return "未添加副本";
            
            int total = book.Items.Count;
            int available = book.Items.Count(i => i.Status == "在馆");
            int borrowed = book.Items.Count(i => i.Status == "借出");
            int reserved = book.Items.Count(i => i.Status == "预约");
            int inRepair = book.Items.Count(i => i.Status == "维修");
            int lost = book.Items.Count(i => i.Status == "丢失");
            
            if (available == total)
                return "全部在馆";
            else if (borrowed == total)
                return "全部借出";
            else if (total == 1)
            {
                // 只有一个副本的情况，直接返回状态
                return book.Items.First().Status;
            }
            else
            {
                // 构建状态字符串，只包含有数量的状态
                var statusParts = new List<string>();
                
                if (available > 0) statusParts.Add($"在馆:{available}");
                if (borrowed > 0) statusParts.Add($"借出:{borrowed}");
                if (reserved > 0) statusParts.Add($"预约:{reserved}");
                if (inRepair > 0) statusParts.Add($"维修:{inRepair}");
                if (lost > 0) statusParts.Add($"丢失:{lost}");
                
                return string.Join(" ", statusParts);
            }
            */
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
           
            
            try
            {
                string keyword = txtSearch.Text.Trim();
                int? categoryId = null;
                
                if (cmbCategory.SelectedIndex > 0 && cmbCategory.SelectedItem != null)
                {
                    var selectedItem = cmbCategory.SelectedItem as ComboBoxItem;
                    categoryId = selectedItem?.Value as int?;
                }
                
                if (_bookService != null)
                {
                    LoadBooks(keyword, categoryId);
                }
                else
                {
                    MessageBox.Show("BookService未初始化", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索过程中发生错误: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnAddBook_Click(object sender, EventArgs e)
        {
            using (var form = new BookDetailForm(null, _categories))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    LoadBooks();
                }
            }
        }

        private void btnEditBook_Click(object sender, EventArgs e)
        {
            if (lvBooks.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要编辑的图书", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            
            var selectedBook = lvBooks.SelectedItems[0].Tag as Book;
            
            using (var form = new BookDetailForm(selectedBook, _categories))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    // 编辑完成后重新加载图书，确保状态刷新
                    // 先完全重新获取图书数据
                    _books = _bookService.GetAllBooks();
                    DisplayBooks();
                }
            }
        }

        private void btnDeleteBook_Click(object sender, EventArgs e)
        {
            if (lvBooks.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要删除的图书", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var selectedBook = lvBooks.SelectedItems[0].Tag as Book;
            var result = MessageBox.Show($"确定要删除《{selectedBook.Title}》吗？这将同时删除所有相关副本！", "确认删除", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
            if (result == DialogResult.Yes)
            {
                bool success = _bookService.DeleteBook(selectedBook.Id);
                if (success)
                {
                    MessageBox.Show("图书删除成功", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    LoadBooks();
                }
                else
                {
                    MessageBox.Show("无法删除图书，可能有副本正在借出中", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnManageItems_Click(object sender, EventArgs e)
        {
            if (lvBooks.SelectedItems.Count == 0)
            {
                MessageBox.Show("请选择要管理副本的图书", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            var selectedBook = lvBooks.SelectedItems[0].Tag as Book;
            using (var form = new BookItemsForm(selectedBook))
            {
                form.ShowDialog();
                LoadBooks();
            }
        }

        private void btnManageCategories_Click(object sender, EventArgs e)
        {
            using (var form = new CategoryManagementForm())
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    LoadCategories();
                    LoadBooks();
                }
            }
        }

        private void lvBooks_DoubleClick(object sender, EventArgs e)
        {
            if (lvBooks.SelectedItems.Count > 0)
            {
                btnEditBook_Click(sender, e);
            }
        }

        // 添加一个公共刷新方法，允许外部调用刷新
        public void RefreshBookList()
        {
            // 重新加载所有图书并刷新显示
            _books = _bookService.GetAllBooks();
            DisplayBooks();
        }
    }

    public class ComboBoxItem
    {
        public string Text { get; set; }
        public object Value { get; set; }
        public override string ToString() => Text;
    }
} 